/**
 * Created by Administrator on 2017/4/20.
 */


var Poker = require('../Poker/Poker');
var PokerRoom = require('../Poker/room').PokerRoom;

var Const = require('./const');
var SubCode = require('../subCode');

var RoundStatus = {
    'WAITING': 1,
    'PREPARE': 2,
    'READY': 3,
}

exports.HFGYZRoom = PokerRoom.extend({
    _roundStatus: RoundStatus.WAITING,
    CurCardInfo : {},
    CurPlayer: 1,
    RoundWinPlayer: 0,
    YaoShaiZi: 0,
    NoCheck: 0,
    init: function(rid, creator, msg) {
        this._super(rid, creator, msg);
        this.CurCardInfo = {
            'Pattern': 0,
            'Cards': [],
            'PlayerIndex': 0,
            'MaxCard': [],
        };
        this.YaoShaiZi = false;
        this.RoundWinPlayer = 0;
        this.CurPlayer = 1;
        this.NoCheck = 0;
        this._roundStatus = RoundStatus.WAITING;
        this._dealerIndex = 1;
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getRoundInfo: function() {
        var info = this._super();
        info.selectWaitMS = this.getHideOption("selectWaitMS");
        return info;
    },

    getReconnectInfo: function(rePlayer) {
        var info = this._super(rePlayer);
        info.curPlay = this.CurPlayer;
        info.roundCardInfo = clone(this.CurCardInfo);
        info.roundCardInfo.maxPoker = [];
        for(var i = 0; i < this.CurCardInfo.MaxCard.length; i++){
            for (var j = 1; j <= 13; j++){
                if(Const.Cost[j] == this.CurCardInfo.MaxCard){
                    info.roundCardInfo.maxPoker.push(j);
                }
            }
        }
        //info.publicCardNum = this._publicCards.getIndex;
        /*info.dealerLZ = this._dealerLZ;
        info.publicCardNum = this._publicCards.getRemainNum();*/
        return info;
    },
    getInfo: function() {
        var info = this._super();
        return info;
    },
    onBeforePlayerReady: function(player) {
        this._super(player);

        if (player == this.getPlayerByUid(this.getCreator())) {
            var subConfig = this.getSubConfig();
            if(this.getPlayerCount() >= subConfig.roomPlayerMin){
                if(this.getReadyPlayerCount() == (this.getPlayerCount() - 1)){
                    return Code.SUCCESS;
                }
                return SubCode.PLAYER_NOT_ALL_READY;
            }else {
                return SubCode.NOT_PLAYER;
            }
        }
        return Code.SUCCESS;
    },
    onAfterPlayerReady: function(player) {
        this._super(player);
        if(player == this.getCreator()){}
        var subConfig = this.getSubConfig();
        if (this.getReadyPlayerCount() >= subConfig.roomPlayerMin && this.getPlayerCount() == this.getReadyPlayerCount()) {

            this._startNewRoundAfter(this.getHideOption("startWaitMS"));
        }
    },

    checkStartNewRound: function() {
        if (this.isPlaying()) {
            return false;
        }
        var subConfig = this.getSubConfig();

        if(this.getPlayerCount() == this.getReadyPlayerCount() && this.getReadyPlayerCount() >= subConfig.roomPlayerMin) {
            return true;
        }
        return false;
    },

    onBeforeStartNewRound: function() {
        this._super();
        this.RoundWinPlayer = 0;
        this.CurPlayer = 1;
        this.NoCheck = 0;
        if(!this.YaoShaiZi){
            var msg = {
                num1: 0,
                num2: 0,
                dealerIndex: 0,
            };
            this.YaoShaiZi = true;
            msg.num1 = ExNumber.rand(6) + 1;
            msg.num2 = ExNumber.rand(6) + 1;
            var num = (msg.num1 + msg.num2) % this.getPlayerCount();
            msg.dealerIndex = 1 + num;
            var player = this.getPlayerByIndex( msg.dealerIndex);
            if(!player){
                msg.dealerIndex = this.getNextPlaying(msg.dealerIndex);
            }
            this._dealerIndex = msg.dealerIndex;

            this.broadcast("onYaoShaiZi", msg);
            //this.broadcast("onFirstRound", {});
        }
        this.broadcast("onDealerChanged", {
            dealer: this._dealerIndex,
            dealerLZ: this._dealerLZ
        });
        /*setTimeout(function() {
            this.settlementCurRound();
        }.bind(this), this.getHideOption("selectWaitMS"));*/
    },

    onAfterStartNewRound: function() {
        this._super();
        this._preStart();
    },
    _preStart: function(){

        this.initPlayersHandCards();
        this.CurPlayer = this._dealerIndex;
        var noCheckPlayer = 0;
        this.enumPlayers(function(eIndex, ePlayer) {
            if(noCheckPlayer){
                return;
            }
            if(ePlayer.checkNoCheck()){
                noCheckPlayer = eIndex;
            }
        },this.CurPlayer);

        logger.debug("room=%d noCheckPlayer %d", this.rid(), noCheckPlayer);
        if(noCheckPlayer) {
            this.RoundWinPlayer = noCheckPlayer;
            this.NoCheck = noCheckPlayer;
            this.settlementCurRound(0);
            return;
        }
        this.startPlay();
    },
    startPlay: function(){
        this._sendCurPlay(true);
    },
    handlePass: function(player, msg, callback){
        if (!this.isPlaying()) {
            callback({code: Code.ROOM_NOT_PLAYING}); return;
        }
        if (!player.isPlaying()) {
            callback({code: Code.PLAYER_NOT_PLAYING}); return;
        }
        if (player.getIndex() != this.CurPlayer) {
            callback({code: SubCode.NOT_CUR_PLAY}); return;
        }
        var MSG = {
            'playerindex' : 0,
        };
        if(!this.CurCardInfo.Pattern) {
            callback({code: SubCode.PATTERN_ERROR});
            return;
        }
        callback({});
        MSG.playerindex = player.getIndex();
        this.broadcast("onPlayerPass", MSG);
        this._nextCurPlay();
    },
    handleGift: function (player, msg, callback) {
        if (isNaN(msg.targetIndex)) {
            callback({code: Code.ARGS_INVALID});
            return;
        }

        var gameConfig = this.getGameConfig();
        var giftType = msg.type;
        var giftConfig = gameConfig.Gift[giftType];
        if (!giftConfig) {
            callback({code: Code.ARGS_VALUE_WRONG});
            return;
        }

        var targetIndex = parseInt(msg.targetIndex);
        var targetPlayer = this.getPlayerByIndex(targetIndex);
        if (!targetPlayer) {
            callback({code: SubCode.INDEX_INVALID});
            return;
        }

        if (!player.checkResource(giftConfig.costs)) {
            callback({code: Code.LACK_OF_COIN});
            return;
        }

        this.broadcast("onPlayerGift", {
            playerIndex: player.getIndex(),
            targetIndex: targetIndex,
            type: giftType
        });
        callback();

        player.costResourceSync(giftConfig.costs);
        // targetPlayer.addResourceSync(giftConfig.harvest);
    },
    handlePlayCard: function(player, msg, callback){
        if (!this.isPlaying()) {
            callback({code: Code.ROOM_NOT_PLAYING}); return;
        }
        if (!player.isPlaying()) {
            callback({code: Code.PLAYER_NOT_PLAYING}); return;
        }
        if (player.getIndex() != this.CurPlayer) {
            callback({code: SubCode.NOT_CUR_PLAY}); return;
        }
        var pattern = msg.pattern;
        var cards = msg.cards;
        if(!pattern){
            callback({code: SubCode.PATTERN_ERROR});
            return;
        }
        logger.debug("room=%d onPlayCard %j,msg %j", this.rid(), this.CurCardInfo,msg);
        //检测玩家手中是否有这些牌
        var handcards = player._handCards.getCards();
        for (var i = 0; i < cards.length; i++){
            if(!handcards.hasOwnProperty(cards[i])) {
                callback({code: SubCode.CARD_NOT_EXIST});
                return;
            }
        }
        if(this.CurCardInfo.Pattern && pattern != Const.Pattern.BOMB) {
            if (pattern != this.CurCardInfo.Pattern) {
                callback({code: SubCode.PATTERN_ERROR});
                return;
            }
            if (cards.length != this.CurCardInfo.Cards.length) {
                callback({code: SubCode.PATTERN_ERROR});
                return;
            }
        }
        var code = 0;
        switch (pattern) {
            case Const.Pattern.SINGLE :
                if (cards.length != 1) {
                    code = SubCode.PATTERN_ERROR;
                }
                if (cards[0] < 100) {
                    code = SubCode.CARD_ERROR;
                }
                break;
            case Const.Pattern.PAIR :
                break;
                if (cards.length != 2) {
                    code = SubCode.PATTERN_ERROR;
                }
                if (Poker.getPoint(cards[0]) != Poker.getPoint(cards[1])) {
                    code = SubCode.CARD_ERROR;
                }
                break;
            case Const.Pattern.SHUNZI :
                if (!player.checkShunZi(cards)) {
                    code = SubCode.PATTERN_ERROR;
                }
                break;
            case Const.Pattern.PAIRS :
                if (!player.checkPairs(cards)) {
                    code = SubCode.PATTERN_ERROR;
                }
                break;
            case Const.Pattern.BOMB :
                if (!player.checkBomb(cards)) {
                    code = SubCode.PATTERN_ERROR;
                }
                break;
        }
        if(code){
            callback({code: code});
            return;
        }
        //记录出牌信息
        if(this.CurCardInfo.Pattern){
            if(pattern == Const.Pattern.BOMB){
                if(this.CurCardInfo.Pattern == Const.Pattern.BOMB){
                    if(cards.length == this.CurCardInfo.Cards.length){
                        var maxCard = player.checkMaxCard(cards);

                        if( maxCard[0]> this.CurCardInfo.MaxCard[0]){
                            this.saveInfo(pattern,cards,player);
                        }else {
                            callback({code: SubCode.PATTERN_ERROR});
                            return;
                        }
                    }else if(cards.length > this.CurCardInfo.Cards.length){
                        this.saveInfo(pattern,cards,player);

                    }else{
                        callback({code: SubCode.PATTERN_ERROR});
                        return;
                    }
                }else {
                    this.saveInfo(pattern,cards,player);

                }
            }else {
                var maxCard = player.checkMaxCard(cards);

                var more = false;
                for (var i = 0; i < maxCard.length; i++){
                    for (var j = 0; j < this.CurCardInfo.MaxCard.length; j++){
                        if(maxCard[i] == this.CurCardInfo.MaxCard[j] + 1){
                            more = true;
                            var arr = [];
                            var index = 0;
                            for(var k = 0; k < maxCard.length; k++){
                                if(maxCard[k] >= maxCard[i]){
                                    arr[index++] = maxCard[k];
                                }
                            }
                            maxCard = arr;
                            break;
                        }
                    }
                    if(more){
                        break;
                    }
                }
                if(pattern == Const.Pattern.PAIR || pattern == Const.Pattern.SINGLE) {
                    if (maxCard[0] == Const.Cost[2] && this.CurCardInfo.MaxCard[0] != Const.Cost[2]) {
                        more = true;
                    }
                }
                if(more){
                    this.saveInfo(pattern,cards,player);
                }else {
                    callback({code: SubCode.PATTERN_ERROR});
                    return;
                }
            }
        }else{
            this.saveInfo(pattern,cards,player);

        }
        player.playCards(cards);

        callback({});
        //广播玩家出牌成功
        var MSG ={
            'pattern': pattern,
            'cards': cards,
            'playerindex': this.CurPlayer,
            'maxPoker': [],
        };
        for(var i = 0; i < this.CurCardInfo.MaxCard.length; i++){
            for (var j = 1; j <= 13; j++){
                if(Const.Cost[j] == this.CurCardInfo.MaxCard[i]){
                    MSG.maxPoker.push(j);
                }
            }
        }
        this.broadcast("onPlayerPlayCard", MSG);
        //将出牌从手牌删除
        player.playCards(cards);
        logger.debug("room=%d handcards %j", this.rid(), player._handCards);
        if(player._handCards.isEmpty()) {
            this.RoundWinPlayer = player.getIndex();
            this.CurCardInfo = {
                'Pattern': 0,
                'Cards': [],
                'PlayerIndex': 0,
                'MaxCard': 0,
            };

            this.enumPlayers(function(eIndex, ePlayer) {
                ePlayer._stat._roundCards = [];
            });

            this.settlementCurRound(0);

            return;
        }
        this._nextCurPlay()
    },
    saveInfo: function(pattern,cards,player){
        this.CurCardInfo.Pattern = pattern;
        this.CurCardInfo.Cards = cards;
        this.CurCardInfo.PlayerIndex = player.getIndex();
        this.CurCardInfo.MaxCard = player.checkMaxCard(cards);
        player._stat._roundCards = cards;
    },
    //切换到下一个玩家
    _nextCurPlay: function(){
        var pass = false;
        this.CurPlayer = this.getNextPlaying(this.CurPlayer);

        if(this.CurPlayer == this.CurCardInfo.PlayerIndex){
            var player = this.getPlayerByIndex(this.CurPlayer);
            this.getNewCard();
            this.CurCardInfo = {
                'Pattern': 0,
                'Cards': [],
                'PlayerIndex': 0,
                'MaxCard': 0,
            };
            this.enumPlayers(function(eIndex, ePlayer) {
                ePlayer._stat._roundCards = [];
            });
            var win = true;
            var cards = player._handCards.getCards();
            ExObject.eachKeyNum(cards, function (c, n) {
                if (c > 100 && n > 0) {
                    win = false;
                }
            });
            if(win){
                this.RoundWinPlayer = player.getIndex();
                this.settlementCurRound(0);
                return;
            }
            pass = true;
        }
        this._sendCurPlay(pass)
    },

    //摸牌
    getNewCard : function(){
        if(this._publicCards.isEmpty()) {
            return;
        }
        var card = this._publicCards.getCard();

        var player = this.getPlayerByIndex(this.CurPlayer);

        player.addNewCard(card);
        var resp = {
            playerindex: this.CurPlayer,
            card: card,
            remain: this._publicCards.getRemainNum()
        };

        this.broadcastReplay("onNewCard", resp);
    },
    onSettlement: function() {
        this._super();

        this.enumPlayers(function(eIndex, ePlayer) {
            ePlayer.settlementPattern();
        });
    },
    getSettlementInfo: function(){
        var info = this._super();
        info.nocheckindex = this.NoCheck;
        var player = this.getPlayerByIndex(this.RoundWinPlayer);
        info.winindex = this.RoundWinPlayer;
        return info;
    },

    onCurRoundFinished: function() {
        this._super();
        if(this._dealerIndex == this.RoundWinPlayer){
            this._dealerLZ++;
        }else{
            this._dealerIndex = this.RoundWinPlayer;
            this._dealerLZ = 1;
        }

        this._roundStatus = RoundStatus.WAITING;
    },

    /******************************************************************
     * 功能接口
     ******************************************************************/


    _startNewRoundAfter: function(timeMS) {
        if (this._roundStatus != RoundStatus.WAITING) {
            return;
        }

        this.broadcast("onRoomStartAfter", {
            time: timeMS,
        });

        this._roundStatus = RoundStatus.PREPARE;

        setTimeout(function() {
            if (this._roundStatus != RoundStatus.PREPARE) {
                return;
            }

            this._roundStatus = RoundStatus.READY;
            this.tryStartNewRound();
        }.bind(this), timeMS);
    },
    /**
     * 广播当前出牌玩家
     * @private
     */
    _sendCurPlay: function(pass) {
        this.broadcastReplay("onCurPlay", {
            "curPlay": this.CurPlayer,
            "pass": pass,

        })
    },
});